import React, { Component } from 'react';
import { StyleSheet, View, Text, Image, Animated, TouchableOpacity, TextInput, ActivityIndicator, Dimensions } from 'react-native';
import { GLOBAL } from '../../../../../config/global';
import { orderStyle, commonStyle } from '../_common/style';
import { style } from '../../../../../theme/style'
import HTTP from '../../../../../utils/http';
import { API, API_GENERATE } from '../../../../../config/api';
import { ProductSelect } from './_components/ProductSelect';
import { Common } from '../../../../../component/common/Common';
import { CommonDialog } from '../../../../../components/common/Dialog';
import { ProductEditing } from '../../../highSeas/_components/ProductEditing';
import { productSelectStyle } from '../../../highSeas/_common/style';
import { ProgressModal } from './_components/ProgressModal';
import ToastUtil from '../../../../../utils/toast';
import { Item } from 'native-base';

const scale = GLOBAL.SCALE;
const query = require('../../../../../imgs/global/query.png');
const selectIcon = require('../../../../../imgs/select.png');
export class GoodsDetail extends Component {
	static navigationOptions = ({ navigation }) => {
		return {
			headerTitle: '产品详情',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			}
		}
	};

	constructor(props) {
		super(props);
		const { data, choice } = this.props.navigation.state.params;
		this.data = data || {};
		this.choice = choice;
		this.state = {
			optionBox: false,
			goodsModal: true,
			modalVisible: false,
			seaModalVisible: false,
			assignModalVisible: false,
			submitType: 'COMMON',
			mainObjectText: '请选择接收人',
			modalObj: {
				currSelectIndex: -1,
				currTitle: '',
				currlistData: [],
				currCb: null,
				currIsVisible: false,
			},
			bannerContent: null,
			middleContent: () => {
				return (<View></View>)
			},
			lightBoxData: {
				modalVisible: false,
				onClosePress: this._closeLightBox,
				title: '日志',
				rowDataList: [],
			},
			bizTeamUserList: [],
			goodsNum: 0,
			loading: false
		}

		this.postParams = {
			applyType: '',
			comments: '',
			bizStaffId: data.staffId || '',
			companyId: data.companyId || '',
			goodsCategoryList: []
		}
	}

	componentWillMount () {
		this._getStaffGoodsDetail();
	}

	async _getStaffGoodsDetail () {
		const { bizTeamUserList } = this.state;
		const { companyId, staffId } = this.data;
		let staffGoodsDetail = await HTTP.POST(API_GENERATE(API.GET_STAFF_GOODS_DETAIL), { companyId, bizStaffId: staffId, corpId: this.choice.corpId });
		let bizTeamUserResponse = await HTTP.POST(API_GENERATE(API.GET_BIZ_TEAMUSER_LIST), { bizStaffId: staffId, corpId: this.choice.corpId });

		bizTeamUserResponse && bizTeamUserResponse.length && bizTeamUserResponse.map((item, index) => {
			bizTeamUserList.push({ dictName: item.staffName, dictKey: item.staffId })
		})

		this.setState({ staffGoodsDetail, bizTeamUserList })
	}

	async	_getLogList (goodsId) {
		const { companyId } = this.data;
		let goodsLogList = await HTTP.POST(API_GENERATE(API.GET_GOODS_LOG_LIST), { companyId, goodsId });
		if (!goodsLogList || !goodsLogList.length) {
			ToastUtil.showSuccess('该产品没有日志信息');
			return
		};
		goodsLogList = goodsLogList && goodsLogList.map((item) => {
			if (item.auditResult == 9) {
				item.auditResultName = '操作';
			}
			return item;
		})
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = true;
		lightBoxData.rowDataList = goodsLogList;
		this.setState({
			lightBoxData,
			status: 'data'
		})
	}

	_closeLightBox = () => {
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = false;
		this.setState({ lightBoxData });
	}


	_getMainType = (index) => {
		this.postParams.bizStaffId = this.state.bizTeamUserList[index].dictKey;
		this.setState({
			mainTypeSelectIndex: index,
			mainObjectText: this.state.bizTeamUserList[index].dictName
		})
		this._closeModal();
	}

	_closeModal = () => {
		let { modalObj } = this.state;
		modalObj.currIsVisible = false;
		this.setState({ modalObj });
	}

	_openModal () {
		let { modalObj, bizTeamUserList } = this.state;
		modalObj.currIsVisible = true;
		modalObj.currTitle = '请选择接收人';
		modalObj.currlistData = bizTeamUserList;
		modalObj.currSelectIndex = this.state.mainTypeSelectIndex;
		modalObj.currCb = this._getMainType;
		this.setState({ modalObj }, () => {
		});
	}

	//取消-清空所以选择
	_cancelMiddleContent () {
		const { staffGoodsDetail } = this.state;
		const { goodsCategoryList } = staffGoodsDetail || {};
		this.postParams.goodsCategoryList = [];
		this.postParams.bizStaffId = '';

		goodsCategoryList && goodsCategoryList.map((item, index) => {
			item.select = false;
			item.goodsList && item.goodsList.map((subItem, index) => {
				subItem.select = false;
			})
		})

		this.setState({
			submitType: 'COMMON',
			optionBox: false,
			goodsNum: 0,
			mainObjectText: '请选择接收人',
			mainTypeSelectIndex: '',
			staffGoodsDetail
		}, () => this._renderMiddleContent())
	}

	//选择商品
	_getGoodsCode = (data) => {
		this.postParams.goodsCategoryList = [];
		for (var i = 0; i < data.length; i++) {
			const element = data[i].goodsList
			for (var j = 0; j < element.length; j++) {
				const data = element[j]
				if (data.select) {
					this.postParams.goodsCategoryList.push(data.goodsCode);
				}
			}
		}
		this.setState({ goodsNum: this.postParams.goodsCategoryList.length }, () => { this._renderMiddleContent() })
	}

	//确认投公海or分配
	async _submit (type) {
		if (this.request) return;
		this.setState({ assignModalVisible: false, seaModalVisible: false });
		if (type == 'TRANS' && !this.state.comments) {
			ToastUtil.showWarning('请填写备注');
			return;
		}

		this.request = true;
		this.postParams.applyType = type;
		this.postParams.comments = this.state.comments;
		this.postParams.corpId = this.choice.corpId;
		this.setState({ loading: true });
		let res = await HTTP.POST(API_GENERATE(API.ADD_COMPANY_PRODUCT), this.postParams);
		if (res) {
			this.setState({ loading: false });
			ToastUtil.showSuccess(`提交成功`).then(() => {
				this.request = false;
				this.setState({
					goodsNum: 0,
					bizTeamUserList: [],
					goodsCategoryList: []
				}, () => {
					this._getStaffGoodsDetail();
					this._renderMiddleContent();
				})
			})
		} else {
			this.setState({ loading: false });
			this.request = false;
		}

	}

	_renderToastWrap () {
		return (
			<View>
				<Text style={styles.toasText}>1.投公海：</Text>
				<Text style={styles.toasText}>投公海无需走审批。</Text>
				<Text style={styles.toasText}>投海成功后，如业务名下与该企业无任何关联的产品，则与企业关系解除。</Text>
				<Text style={styles.toasText}>2.产品分配：</Text>
				<Text style={styles.toasText}>产品分配需走对应审批。</Text>
				<Text style={styles.toasText}>业务仅支持转移给同产品组同伴，分配成功后，如业务名下与该企业无任何关联的产品，则与企业关系解除。</Text>
			</View>
		)
	}

	_renderSeaToastWrap = () => {
		const { goodsNum } = this.state;
		return (
			<View>
				<Text style={styles.toasText}>本次投公海分类 ：{goodsNum}个，是否确认操作？</Text>
				<ShortButton btnText={'确认'} onPress={() => this._submit('THROW')} />
			</View>
		)
	}

	_renderAssignToastWrap = () => {
		const { goodsNum, mainObjectText } = this.state;
		return (
			<View>
				<Text style={styles.toasText}>本次分配分类 {goodsNum}个，接收人：{mainObjectText}</Text>
				<View style={[styles.row, { marginBottom: 5 * scale }]}>
					<Text style={{ color: 'red', marginRight: 3 * scale }}>*</Text><Text style={{ fontSize: 12 * scale }}>备注</Text>
				</View>
				<TextInput
					style={styles.textInput}
					placeholder={"请输入备注，限定1000字。"}
					placeholderTextColor={"#B4B8C0"}
					value={this.state.comments}
					maxLength={1000}
					multiline={true}
					onChangeText={(comments) => this.setState({ comments })}
				/>
				<ShortButton btnText={'确认'} onPress={() => this._submit('TRANS')} />
			</View>
		)
	}

	_renderMiddleContent () {
		let { submitType, mainMethodText, goodsNum } = this.state;
		if (submitType == 'COMMON') {
			this.setState({
				bannerContent: null,
				middleContent: () => {
					return (<View></View>)
				},
				renderRight: null,
			})
		} else if (submitType == 'SEND') {
			this.setState({
				bannerContent: null,
				middleContent: () => {
					return (
						<View style={styles.middleText}>
							<Text style={{ fontSize: 12 * scale, }}>本次选择投海数：{goodsNum}</Text>
						</View>
					)
				},
				renderRight: () => {
					return (
						<View style={productSelectStyle.topBtns}>
							<Text style={productSelectStyle.topBtnText} onPress={() => this.setState({ seaModalVisible: true })}>确认投公海</Text>
							<Text style={productSelectStyle.topBtnText} onPress={() => this._cancelMiddleContent()}>取消</Text>
						</View>
					)
				},
			})
		} else {
			this.setState({
				bannerContent: () => {
					return (
						<View style={styles.bannerText}>
							<Text style={{ fontSize: 12 * scale, }}>本次选择分配数：{goodsNum}</Text>
						</View>
					)
				},
				middleContent: () => {
					return (
						<TouchableOpacity activeOpacity={1} onPress={() => {
							this._openModal();
						}} style={styles.assignMiddle}>
							<Text style={{ fontSize: 12 * scale, color: '#999898' }}>{this.state.mainObjectText}</Text>
							<Image source={selectIcon} style={{ tintColor: '#000', width: 12 * scale, height: 6 * scale }} />
						</TouchableOpacity>
					)
				},
				renderRight: () => {
					return (
						<View style={productSelectStyle.topBtns}>
							<Text style={productSelectStyle.topBtnText} onPress={() => this.setState({ assignModalVisible: true, comments: '' })}>确认分配</Text>
							<Text style={productSelectStyle.topBtnText} onPress={() => this._cancelMiddleContent()}>取消</Text>
						</View>
					)
				},
			})
		}
	}

	render () {
		const { modalObj, modalVisible, staffGoodsDetail, middleContent, renderRight, bannerContent, seaModalVisible,
			assignModalVisible, lightBoxData, loading, optionBox } = this.state;
		const { goodsCategoryList, bizStaffInfo } = staffGoodsDetail || {};
		const { userName, mobileNo, userTeamList, organName } = bizStaffInfo || {};
		return (
			<View style={styles.back}>
				<View style={styles.topInfo}>
					<View style={[styles.row, styles.rowView]}>
						<Text style={[styles.text, styles.label]}>产品组</Text>
						<View style={[styles.row, { flex: 1, flexWrap: 'wrap' }]}>
							{
								userTeamList && userTeamList.length ?
									userTeamList.map((item, index) => {
										return (<Text key={index} style={[styles.text, { marginRight: 5 * scale }]}>{item.teamName}</Text>)
									}) : <Text style={styles.text}>{'-'}</Text>
							}
							<Text style={styles.text}>|  {organName || '-'}</Text>
						</View>
					</View>
					<View style={[styles.row, styles.rowView]}>
						<Text style={[styles.text, styles.label]}>业务员</Text>
						<Text style={styles.text}>{userName || '-'} {mobileNo || ''}</Text>
						<View style={[styles.row, { flex: 1, justifyContent: 'flex-end' }]}>
							<TouchableOpacity onPress={() => this.setState({ modalVisible: true })} >
								<Image style={{ tintColor: '#fff' }} source={query} />
							</TouchableOpacity>
							<Text style={[styles.text, styles.btns]} onPress={() => this.setState({
								submitType: 'SEND', optionBox: true
							}, () => this._renderMiddleContent())} >投公海</Text>
							<Text style={[styles.text, styles.btns]}>|</Text>
							<Text style={[styles.text, styles.btns]} onPress={() => this.setState({
								submitType: 'ASSIGN', optionBox: true
							}, () => this._renderMiddleContent())} >分配</Text>
						</View>
					</View>
				</View>

				<ProductEditing
					// searchPress={(searchCode) => this._getGoodsData(searchCode)}
					getLogList={(goodsId) => this._getLogList(goodsId)}
					data={goodsCategoryList || []}
					middleContent={middleContent}
					renderRight={renderRight}
					bannerContent={bannerContent}
					confirmData={(data) => this._getGoodsCode(data)}
					secondRight={true}
					optionBox={optionBox}
					showLossInfo={true}
					showLogInfo={true}
				/>

				{/* 审批流 */}
				<ProgressModal {...lightBoxData} />
				<CommonDialog modalVisible={modalVisible} title={'提示'} onClosePress={() => { this.setState({ modalVisible: false }) }} renderCustom={this._renderToastWrap} />
				<CommonDialog modalVisible={seaModalVisible} title={'提示'} onClosePress={() => { this.setState({ seaModalVisible: false }) }} renderCustom={this._renderSeaToastWrap} />
				<CommonDialog modalVisible={assignModalVisible} title={'提示'} onClosePress={() => { this.setState({ assignModalVisible: false }) }} renderCustom={this._renderAssignToastWrap} />
				<Common type="modal" demoData={(
					<Common type="listRadio"
						selectIndex={modalObj.currSelectIndex}
						title={modalObj.currTitle}
						listData={modalObj.currlistData || []}
						selectCallBack={modalObj.currCb}
					/>
				)}
					isVisible={modalObj.currIsVisible}
					closeCallballFn={this._closeModal}
				/>

				{
					loading ?
						<View style={styles.loadingView}>
							<View style={styles.loadedCell}>
								<ActivityIndicator
									animating={true}
									color={'#fff'}
									size="small"
								/>
							</View>
						</View> : null
				}
			</View>
		)
	}
}

export function ShortButton (props) {
	let { btnText, onPress } = props || {};
	return (
		<TouchableOpacity style={styles.btn} onPress={onPress}>
			<Text style={styles.btnText}>{btnText}</Text>
		</TouchableOpacity>
	)
}

const styles = StyleSheet.create({
	back: {
		flex: 1,
		backgroundColor: "#0087FF"
	},
	topInfo: {
		backgroundColor: style.color.themeColor
	},
	row: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	rowView: {
		margin: 12 * scale,
	},
	text: {
		color: '#fff',
		fontSize: 12 * scale,
		fontWeight: 'bold',
		lineHeight: 18 * scale
	},
	label: {
		marginRight: 18 * scale,
		width: 66 * scale,
		textAlign: 'right'
	},
	btns: {
		paddingLeft: 8 * scale
	},
	toasText: {
		fontSize: 12 * scale,
		marginBottom: 14 * scale
	},
	middleText: {
		flex: 1,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
		flexDirection: 'row',
		alignItems: 'center',
	},
	bannerText: {
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
	},
	assignMiddle: {
		flex: 1,
		backgroundColor: '#F4F7FE',
		borderRadius: 4 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
		marginLeft: 12 * scale,
		marginRight: 12 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between'
	},
	btn: {
		backgroundColor: style.color.themeColor,
		borderRadius: 14 * scale,
		marginLeft: '32%',
		marginRight: '32%',
		marginTop: 10 * scale,
		paddingTop: 10 * scale,
		paddingBottom: 10 * scale,
	},
	btnText: {
		color: '#fff',
		textAlign: 'center',
		fontSize: 14 * scale,
		fontWeight: 'bold'
	},
	textInput: {
		borderWidth: 1 * scale,
		borderColor: '#000',
		borderRadius: 4 * scale,
		padding: 10 * scale,
		height: 122 * scale,
		fontSize: 12 * scale,
	},
	loadedCell: {
		width: 75 * scale,
		height: 75 * scale,
		backgroundColor: 'rgba(0, 0, 0, .5)',
		borderRadius: 7,
		justifyContent: 'center',
		alignItems: 'center',
		marginLeft: 150 * scale,
		marginTop: (Dimensions.get('window').height - 160) / 2,
	},
	loadingView: {
		width: 375 * scale,
		height: Dimensions.get('window').height,
		backgroundColor: 'rgba(0, 0, 0, 0.1)',
		position: 'absolute',
		top: 0
	}
})